package cn.stylefeng.guns.modular.business.frequency.cmdriver.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.stylefeng.guns.core.exception.ServiceException;
import cn.stylefeng.guns.core.factory.PageFactory;
import cn.stylefeng.guns.core.pojo.page.PageResult;
import cn.stylefeng.guns.modular.business.frequency.cmdriver.entity.CmDriver;
import cn.stylefeng.guns.modular.business.frequency.cmdriver.mapper.CmDriverMapper;
import cn.stylefeng.guns.modular.business.frequency.cmdriver.model.param.CmDriverParam;
import cn.stylefeng.guns.modular.business.frequency.cmdriver.service.CmDriverService;
import cn.stylefeng.guns.modular.business.frequency.cmdriver.enums.CmDriverExceptionEnum;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * 通讯录司机表 服务实现类
 *
 * @author yujie
 * @date 2023/05/09 17:17
 */
@Service
public class CmDriverServiceImpl extends ServiceImpl<CmDriverMapper, CmDriver> implements CmDriverService {

    @Override
    public PageResult<CmDriver> page(CmDriverParam cmDriverParam) {

        // 构造条件
        LambdaQueryWrapper<CmDriver> queryWrapper = new LambdaQueryWrapper<>();

        // 查询分页结果
        return new PageResult<>(this.page(PageFactory.defaultPage(), queryWrapper));
    }

    @Override
    public List<CmDriver> list(CmDriverParam cmDriverParam) {

        // 构造条件
        LambdaQueryWrapper<CmDriver> queryWrapper = new LambdaQueryWrapper<>();

        return this.list(queryWrapper);
    }

    @Override
    public void add(CmDriverParam cmDriverParam) {

        // 将dto转为实体
        CmDriver cmDriver = new CmDriver();
        BeanUtil.copyProperties(cmDriverParam, cmDriver);

        this.save(cmDriver);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void delete(CmDriverParam cmDriverParam) {
        this.removeById(cmDriverParam.getId());
    }

    @Override
    public void edit(CmDriverParam cmDriverParam) {

        // 根据id查询实体
        CmDriver cmDriver = this.queryCmDriver(cmDriverParam);

        // 请求参数转化为实体
        BeanUtil.copyProperties(cmDriverParam, cmDriver);

        this.updateById(cmDriver);
    }

    @Override
    public CmDriver detail(CmDriverParam cmDriverParam) {
        return this.queryCmDriver(cmDriverParam);
    }



    /**
     * 获取通讯录司机表
     *
     * @author yujie
     * @since 2023/05/09 17:17
     */
    private CmDriver queryCmDriver(CmDriverParam cmDriverParam) {
        CmDriver cmDriver = this.getById(cmDriverParam.getId());
        if (ObjectUtil.isEmpty(cmDriver)) {
            throw new ServiceException(CmDriverExceptionEnum.NOT_EXISTED);
        }
        return cmDriver;
    }
}